//
//  Weather update client in go
//  Connects SUB socket to tcp://localhost:5556
//  Collects weather updates and finds avg temp in zipcode
//
package main

import (
	"fmt"
	"os"
	"zmq"
	"flag"
	"strings"
	"strconv"
)

var (
	zip = flag.String("zip", "10001", "Subscribe to zipcode, default is NYC, 10001")
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	subscriber, err := context.Socket(zmq.SUB)
	if err != nil {
		return err
	}
	defer subscriber.Close()

	fmt.Println("Collecting updates from weather server...")
	err = subscriber.Connect("tcp://localhost:8100")
	if err != nil {
		return err
	}
	filter := append([]byte(*zip), ' ')
	err = subscriber.SetOptionByte(zmq.SUBSCRIBE, filter)
	if err != nil {
		return err
	}
	var update_nbr int64
	var total_temp int64
	for i := 0; i < 100; i++ {
		updata, err := subscriber.Recv(0)
		if err != nil {
			return err
		}
		fmt.Printf("updata %d %s\n", i, updata)
		ar := strings.Split(string(updata), " ")
		if len(ar) == 3 {
			i, err := strconv.Atoi64(ar[1])
			if err != nil {
				return err
			}
			total_temp += i
			update_nbr++
		}
	}
	if update_nbr != 0 {
		fmt.Printf("Average temperature for zipcode '%s' was %dF\n", *zip, total_temp/update_nbr)
	}
	return nil
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Weather update client")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}